package com.tang.springbootsecurity.service;/*
 *   @author Dram
 *   @create 2021-05-06 13:45
 */

import com.tang.springbootsecurity.dao.UserDao;
import com.tang.springbootsecurity.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpringDataUserDetailsService implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);

        //连接数据库来查询用户
        UserDto user = userDao.getUserByUsername(username);
        if (user == null){
            //如果用户查不到 返回nul 由provider来抛出异常 自己不要手动抛异常
            return null;
        }

        List<String> permissionsByUserId = userDao.findPermissionsByUserId(user.getId());
        String[] permissionArray = new String[permissionsByUserId.size()];
        permissionsByUserId.toArray(permissionArray);
        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities(permissionArray).build();

        return userDetails;
    }
}
